<script lang="ts" setup>
import type { VxeGridListeners, VxeGridProps } from '#/adapter/vxe-table';
import { ref, h } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { useDebounceFn } from '@vueuse/core';
import {
  Button,
  message,
  Input,
  InputNumber,
  Spin,
  Divider,
} from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { useVbenForm } from '#/adapter/form';
import {
  getChangeStockRecordInfo,
  doChangeStockRecordAdd,
  doChangeStockRecordEdit,
  doChangeStockRecordApproval,
  doChangeStockRecordAgainst,
  doChangeStockRecordDelete,
} from '#/api/changeStockRecord';
import { AntPlusOutlined } from '@vben/icons';
import Warehouse from '../../modules/warehouse.vue';
import MaterialSku from '../../modules/materialSku.vue';

interface RowType {
  material_id: string;
  action_num: number;
  material_sku_id: number;
  material_name: string;
  price: string;
  unit_rate: number;
  stock: number;
  unit: string;
  total_price: string;
  cloth_width: string;
  gram_weight: string;
  remark: string;
  _X_ROW_KEY?: string;
}

const emit = defineEmits(['fetchData']);

const keyword = ref<Record<string, string>>({
  in_ware_house_id: '',
  out_ware_house_id: '',
});
const submitLoading = ref(false);
const routerData = ref<any>({});
const RecordId = ref(0);
const formData = ref<any>({
  bom_list: [],
  posted: 0,
});
const isDisabled = ref(true);
const shareData = (res: any) => {
  console.log('shareData', res);
  if (res.shareType && res.shareType === 'warehouse') {
    doWarehouseList(res);
  } else {
    doMaterialList(res);
  }
  return;
};

const doWarehouseList = (res: any) => {
  if (res.list && res.list.length > 0) {
    const warehouse = res.list[0];

    if (res.pageParams.params.field === 'in_ware_house_id') {
      formApi.setValues({ in_ware_house_id: warehouse.code_name });
    } else {
      formApi.setValues({ out_ware_house_id: warehouse.code_name });
    }
  }
};
const doMaterialList = async (res: any) => {
  if (res.list && res.list.length > 0) {
    const currentTableData = gridApi.grid.getData() || [];
    const newRows = res.list.map((item: any) => ({
      purchase_bom_detail_id: item.purchase_bom_detail_id, // 物料ID
      material_sku_id: item.material_sku_id, // 物料skuID
      material_id: item.material_id, // 物料ID
      material_name: item.material_name, // 物料名称
      num: 0, // 数量
      record_detail_id: 0,
      price: item.price || 0, // 物料单价，默认为0
      // total_price: item.price, // 总价
      unit: item.unit, // 单位
      unit_rate: item.unit_rate, // 换算比例
      stock: item.stock, // 库存
      cloth_width: item.cloth_width, // 幅宽
      gram_weight: item.gram_weight, // 克重
      remark: '', // 备注，默认为空
      less_num: item.less_num, // 应收数量
      confirm_num: item.confirm_num, // 应收数量
      reviced_num: item.reviced_num, // 已收数量
    }));
    const updatedTableData = [...currentTableData, ...newRows];
    gridApi.setGridOptions({
      data: updatedTableData,
    });
    message.success(`成功添加 ${res.list.length} 条物料`);
  } else {
    message.warning('未选择任何物料');
  }
};

const openAddMaterial = async () => {
  const formValues = await formApi.getValues();
  if (!formValues.out_ware_house_id) {
    message.warning('请选择调出仓库');
    return;
  }
  PurchaseModalApi.setData({
    query: {},
  }).open();
};

const [WarehouseModal, WarehouseApi] = useVbenModal({
  connectedComponent: Warehouse,
});
const [PurchaseModal, PurchaseModalApi] = useVbenModal({
  connectedComponent: MaterialSku,
});

const handleDelete = (row: RowType) => {
  if (gridApi) {
    const currentData = gridApi.grid.getData();
    const index = currentData.findIndex(
      (item: any) => item._X_ROW_KEY === row._X_ROW_KEY,
    );
    if (index !== -1) {
      currentData.splice(index, 1);
      gridApi.setGridOptions({
        data: currentData,
      });
    }
  }
};

const onSubmit = async () => {
  const { valid } = await formApi.validate();
  if (valid) {
    submitLoading.value = true;
    try {
      let saveData = await formApi.getValues();
      if (gridApi) {
        const tableData = gridApi.grid.getData();
        saveData.bom_list = tableData;
      }
      if (RecordId.value) {
        await doChangeStockRecordEdit({
          ...saveData,
          record_id: RecordId.value,
        });
      } else {
        await doChangeStockRecordAdd(saveData);
      }
      message.success('保存成功');
      modalApi.close();
      emit('fetchData');
    } finally {
      submitLoading.value = false;
    }
  }
};
const handleSubmit = useDebounceFn(async () => {
  await onSubmit();
}, 300);
const handleAgainstToApproval = async (type: string) => {
  try {
    if (type === 'approval') {
      await doChangeStockRecordApproval({ ids: [RecordId.value] });
    } else {
      await doChangeStockRecordAgainst({ ids: [RecordId.value] });
    }
    message.success('操作成功');
    emit('fetchData');
    modalApi.close();
  } catch (error) {}
};

// Delete Record
const handleDeleteRecord = async () => {
  try {
    await doChangeStockRecordDelete({ ids: [RecordId.value] });
    message.success('删除成功');
    emit('fetchData');
    modalApi.close();
  } catch (error) {
    console.error('删除失败:', error);
  }
};

// 初始化
const initClear = async () => {
  RecordId.value = 0;
  formApi.setValues({});
  if (gridApi) {
    gridApi.setGridOptions({
      data: [],
    });
  }
  Object.keys(keyword.value).forEach((key: string) => {
    keyword.value[key] = '';
  });
};
const init = async () => {};

const disabledOn = async () => {
  isDisabled.value = true;
  formApi.setState({ commonConfig: { disabled: true } });
};
const disabledOff = async () => {
  isDisabled.value = false;
  formApi.setState({ commonConfig: { disabled: false } });
};

const fetchData = async () => {
  if (RecordId.value) {
    try {
      const res = await getChangeStockRecordInfo({ record_id: RecordId.value });
      formApi.setValues(res.row);
      formData.value.posted = res.row.posted;
      if (gridApi) {
        gridApi.setGridOptions({
          data: res.row.bom_list || [],
        });
      }
      Object.keys(keyword.value).forEach((key: string) => {
        if (res.row[key]) {
          keyword.value[key] = 'initValue:' + res.row[key];
        }
      });
    } catch (error) {
      console.error('获取详情失败:', error);
    }
  }
};

const gridOptions: VxeGridProps<RowType> = {
  border: true,
  pagerConfig: {
    enabled: false,
  },
  columns: [
    { type: 'seq', width: 60, title: '序号' },
    { field: 'material_name', width: 350, title: '物料名称' },
    {
      field: 'action_num',
      width: 120,
      title: '数量',
      editRender: {},
      slots: { edit: 'actionNum' },
    },
    { field: 'stock', width: 100, title: '库存' },
    { field: 'unit', width: 100, title: '单位' },
    { field: 'price', width: 90, title: '单价' },
    // { field: 'total_price', width: 100, title: '总价' },
    { field: 'unit_rate', width: 80, title: '换算比例' },
    { field: 'cloth_width', width: 80, title: '幅宽' },
    { field: 'gram_weight', width: 100, title: '克重' },
    {
      field: 'remark',
      title: '备注',
      width: 300,
      editRender: {},
      slots: { edit: 'remark' },
    },
    {
      field: 'operation',
      width: 120,
      title: '操作',
      slots: { default: 'operation' },
    },
  ],
  data: [],
  height: '300px',
  editConfig: {
    mode: 'cell',
    trigger: 'click',
  },
};

const gridEvents: VxeGridListeners<RowType> = {
  cellClick: ({ row }) => {
    // message.info(`cell-click: ${row.material_name}`);
  },
  editClosed: (res) => {
    // if (res.column.field === 'action_num') {
    //   const row = res.row
    //   const actionNum = Number(row.action_num) || 0
    //   const price = Number(row.price) || 0
    //   row.total_price = (actionNum * price).toFixed(2)
    // }
  },
};

const [Grid, gridApi] = useVbenVxeGrid({
  gridEvents,
  gridOptions,
});

const [Form, formApi] = useVbenForm({
  commonConfig: {
    disabled: true,
    componentProps: {
      class: 'w-full',
    },
  },
  showDefaultActions: false,
  layout: 'horizontal',
  schema: [
    {
      component: 'Input',
      fieldName: 'record_sn',
      label: '调拨单号',
      componentProps: {
        disabled: true,
        placeholder: '自动生成',
      },
    },
    {
      component: 'Input',
      fieldName: 'in_ware_house_id',
      label: '调入仓库',
      componentProps: () => ({
        onClick: (value: any) => {
          WarehouseApi.setData({
            query: { params: { type: '物料', is_stop: 0 } },
            selectType: 'radio',
            params: { field: 'in_ware_house_id' },
          }).open();
        },
      }),
    },
    {
      component: 'Input',
      fieldName: 'out_ware_house_id',
      label: '调出仓库',
      componentProps: () => ({
        onClick: (value: any) => {
          WarehouseApi.setData({
            query: { params: { type: '物料', is_stop: 0 } },
            selectType: 'radio',
            params: { field: 'out_ware_house_id' },
          }).open();
        },
      }),
    },
    {
      component: 'DatePicker',
      fieldName: 'record_date',
      label: '单据日期',
      rules: 'required',
      componentProps: {
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
      },
    },
    {
      component: 'Textarea',
      fieldName: 'remark',
      label: '备注',
      formItemClass: 'col-span-2 col-start-1',
      componentProps: {
        placeholder: '请输入备注',
      },
    },
  ],
  wrapperClass: 'grid grid-cols-4', // Adjusted for better layout
});

const [Modal, modalApi] = useVbenModal({
  class: 'w-4/5',
  appendToMain: true,
  fullscreen: true,
  showConfirmButton: false,
  showCancelButton: false,
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      routerData.value = modalApi.getData<Record<string, any>>();
      initClear();
      if (routerData.value?.info?.record_id) {
        console.log(routerData.value.info.posted);
        if (routerData.value.info.posted == '-') {
          routerData.value.info.posted = 0;
        }
        RecordId.value = routerData.value?.info?.record_id;
      }
      if (RecordId.value) {
        fetchData();
        disabledOn;
      } else {
        disabledOff();
      }
    }
  },
});
</script>

<template>
  <Modal :title="RecordId ? '编辑调拨单' : '新建调拨单'">
    <div class="p-4">
      <!-- Basic Information -->
      <Form />

      <Divider />

      <!-- Material List -->
      <div class="mb-1">
        <div class="mb-2 flex items-center justify-between">
          <h3 class="text-lg font-medium">物料列表</h3>
          <Button
            type="primary"
            @click="openAddMaterial()"
            :disabled="isDisabled"
          >
            <AntPlusOutlined />
            新增物料
          </Button>
        </div>

        <Grid>
          <template #actionNum="{ row, rowIndex }">
            <Input
              v-model:value="row.action_num"
              :disabled="isDisabled"
              :min="0"
              :step="1"
              style="width: 100%"
            />
          </template>

          <template #remark="{ row }">
            <Input
              v-model:value="row.remark"
              :disabled="isDisabled"
              placeholder="备注"
            />
          </template>

          <template #operation="{ row, rowIndex }">
            <Button
              type="link"
              size="small"
              danger
              @click="handleDelete(row)"
              :disabled="isDisabled"
              >删除</Button
            >
          </template>
        </Grid>
      </div>
    </div>

    <!-- Footer Buttons -->
    <template #prepend-footer>
      <div>
        <Button @click="modalApi.close()">取消</Button>
      </div>
      <div class="space-x-2">
        <template v-if="RecordId && isDisabled">
          <Button
            type="ghost"
            class="bg-[#f56c6c] text-white hover:opacity-75"
            @click="
              handleAgainstToApproval(formData.posted ? 'against' : 'approval')
            "
          >
            {{ formData.posted ? '反审' : '审核' }}
          </Button>
          <Button
            type="ghost"
            v-if="!formData.posted"
            class="bg-[#ca2828] text-[#fff] hover:opacity-75"
            @click="handleDeleteRecord()"
            >删除</Button
          >
          <Button
            type="ghost"
            v-if="!formData.posted"
            class="bg-[#f0a62f] text-[#fff] hover:opacity-75"
            @click="disabledOff()"
            >修改</Button
          >
        </template>
        <Button
          v-if="!isDisabled || !RecordId"
          type="primary"
          @click="handleSubmit()"
          :loading="submitLoading"
          :disabled="submitLoading"
          >保存</Button
        >
      </div>
    </template>
    <WarehouseModal @share-data="shareData" />
    <PurchaseModal @share-data="shareData" />
  </Modal>
</template>
